<template>
  <div class="brand-manage">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
          v-model="searchKeyword"
          placeholder="输入品牌名称/负责人"
          clearable
          style="width: 300px"
          @clear="handleSearch"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button type="primary" @click="openDialog(false)">新增品牌</el-button>
    </div>

    <!-- 品牌表格 -->
    <el-table :data="paginatedData" border stripe>
      <el-table-column prop="id" label="ID" width="80" align="center"/>
      <el-table-column prop="name" label="品牌名称" align="center" width="180"/>
      <el-table-column prop="productCount" label="关联商品数" width="120" align="center"/>
      <el-table-column prop="manager" label="负责人" width="120" align="center"/>
      <el-table-column prop="updater" label="最后修改人" width="120" align="center"/>
      <el-table-column prop="createTime" label="创建时间" width="180" align="center"/>
      <el-table-column prop="updateTime" label="修改时间" width="180" align="center"/>
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <template #default="{ row }">
          <el-button type="text" @click="openDialog(true, row)">编辑</el-button>
          <el-button
              type="text"
              style="color: #ff4d4f"
              @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :total="filteredData.length"
        :page-sizes="[9, 15, 25]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        class="pagination"
    />

    <!-- 弹窗组件（直接内嵌） -->
    <el-dialog
        v-model="showDialog"
        :title="isEdit ? '编辑品牌' : '新增品牌'"
        width="500px"

    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="品牌名称" prop="name">
          <el-input
              v-model="form.name"
              placeholder="如：电子产品"
              maxlength="20"
              show-word-limit
          />
        </el-form-item>

      </el-form>

      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, computed, reactive, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {addBrand, deleteBrand, getAllBrandsInfo, updateBrand} from "@/api/auth.js";


const rawData = ref([
  {
    id: 1,
    name: '电子产品',
    productCount: 3,
    manager: '周兴',
    updater: '周兴',
    createTime: '2025-04-23 20:15:46',
    updateTime: '2025-04-23 20:15:46'
  },
  {
    id: 2,
    name: '家居用品',
    productCount: 3,
    manager: '周兴',
    updater: '周兴',
    createTime: '2025-04-23 20:15:46',
    updateTime: '2025-04-23 20:15:46'
  },
  {
    id: 3,
    name: '服装鞋帽',
    productCount: 1,
    manager: '周兴',
    updater: '周兴',
    createTime: '2025-04-23 20:15:46',
    updateTime: '2025-04-23 20:15:46'
  },
  {
    id: 4,
    name: '手机',
    productCount: 2,
    manager: '周兴',
    updater: '周兴',
    createTime: '2025-04-23 20:15:46',
    updateTime: '2025-04-23 20:15:46'
  },
  {
    id: 5,
    name: '笔记本电脑',
    productCount: 0,
    manager: '周兴',
    updater: '周兴',
    createTime: '2025-04-23 20:15:46',
    updateTime: '2025-04-23 20:15:46'
  },
  {
    id: 6,
    name: '智能手表',
    productCount: 1,
    manager: '周兴',
    updater: '周兴',
    createTime: '2025-04-23 20:15:46',
    updateTime: '2025-04-23 20:15:46'
  }
])
const initData = async () => {
  try {
    const res = await getAllBrandsInfo()
    if (res.code === 200) {
      rawData.value = res.data
    } else {
      ElMessage.error(res.message)
    }
  } catch (e) {
    ElMessage.error(e)
  }


}
onMounted(() => {
  initData()
})

// 搜索分页逻辑
const searchKeyword = ref('')
const pagination = ref({current: 1, size: 9})

const filteredData = computed(() => {
  return rawData.value.filter(item =>
      item.name.includes(searchKeyword.value) ||
      item.manager.includes(searchKeyword.value)
  )
})

const paginatedData = computed(() => {
  const start = (pagination.value.current - 1) * pagination.value.size
  return filteredData.value.slice(start, start + pagination.value.size)
})

const handleSearch = () => pagination.value.current = 1

// 弹窗控制
const showDialog = ref(false)
const isEdit = ref(false)
const currentRow = ref(null)

// 表单数据
const form = reactive({
  name: '',
  id: ''

})

// 验证规则
const rules = {
  name: [
    {required: true, message: '品牌名称不能为空', trigger: 'blur'},
    {max: 20, message: '最多20字符', trigger: 'blur'}
  ],
  manager: [{required: true, message: '负责人不能为空', trigger: 'blur'}]
}

// 打开弹窗
const openDialog = (editMode, rowData) => {

  isEdit.value = editMode
  if (editMode && rowData) {

    form.id = rowData.id
    // 编辑模式：填充当前行数据
    form.name = rowData.name

  } else {
    // 新增模式：重置表单
    form.name = ''

  }
  showDialog.value = true
}

// 提交表单
const formRef = ref()
const submitForm = async () => {
  try {
    if (isEdit.value) {
      try {
        const res = await updateBrand(form)
        if (res.code === 200) {
          ElMessage.success('修改成功')


        } else {
          ElMessage.error(res.message)


        }


      } catch (e) {
        ElMessage.error(e)
      }


    } else {
      try {
        const res = await addBrand(form.name)
        if (res.code === 200) {
          ElMessage.success('添加成功!')
        } else {
          ElMessage.error(res.message)
        }
      } catch (e) {
        ElMessage.error(e)
      }
    }
    await initData()
    form.id = ''
    form.name = ''
    showDialog.value = false
  } catch (error) {
    console.error('提交失败:', error)
  }
}


// 删除逻辑
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确认删除品牌 "${row.name}" 吗？`,
        '警告',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
          distinguishCancelAndClose: true
        }
    )
    const res = await deleteBrand(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(res.message)
    }
  } catch (error) {
    if (error === 'cancel' || error === 'close') return
    ElMessage.error('删除失败:' + error.message)
  }
  await initData()
}
</script>

<style scoped>
.brand-manage {
  padding: 20px;
  background: #fff;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.el-table {
  margin-top: 10px;
}

.el-dialog .el-input {
  width: 80%;
}
</style>